from flask import Flask, render_template, request, jsonify, session
from database import init_db, get_questions, save_result, check_answers
import random
import sqlite3

app = Flask(__name__)
app.secret_key = 'your-secret-key'  # 请更改为随机字符串

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/test')
def test():
    questions = get_questions()
    session['questions'] = questions
    return render_template('test.html', questions=questions)

@app.route('/submit', methods=['POST'])
def submit():
    answers = request.json
    
    # 计算得分
    score = check_answers(answers)
    
    # 保存结果
    result_id = save_result(score, answers)
    
    return jsonify({
        'score': score,
        'result_id': result_id
    })

@app.route('/result/<result_id>')
def result(result_id):
    # 从数据库获取结果
    conn = sqlite3.connect('friendship_test.db')
    c = conn.cursor()
    c.execute("SELECT score FROM results WHERE id = ?", (result_id,))
    row = c.fetchone()
    conn.close()
    
    if row is None:
        return "结果未找到", 404
        
    score = row[0]
    return render_template('result.html', score=score)

if __name__ == '__main__':
    init_db()
    app.run(host="0.0.0.0",debug=True)